package utils

import (
	"errors"
	"github.com/gofiber/fiber/v2"
	jwtware "github.com/gofiber/jwt/v2"
	"github.com/golang-jwt/jwt/v4"
	"go_cms/app/dto"

	"time"
)

const jtwSecret = "secret"


// token中间件，验证请求是否合法
func Auth() func(*fiber.Ctx) error {
	return jwtware.New(jwtware.Config{
		SigningKey:   []byte(jtwSecret),
		ErrorHandler: func(ctx *fiber.Ctx, err error) error {
			return ctx.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"code": 1, "data": "Missing token",
			})
		},
	})
}

func SetToken(data dto.TokenDto) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	claims:=token.Claims.(jwt.MapClaims)
	claims["name"] = data.Username
	claims["uid"] = data.Id
	claims["exp"]= time.Now().Add(time.Hour*24*7).Unix() //a week

	return token.SignedString([]byte(jtwSecret))
}

func GetToken(ctx *fiber.Ctx) (token dto.TokenDto, err error) {
	user := ctx.Locals("user").(*jwt.Token)
	claims := user.Claims.(jwt.MapClaims)
	if claims != nil {
		token.Username = claims["name"].(string)
		token.Id = claims["uid"].(string)
		return token, nil
	} else {
		return dto.TokenDto{}, errors.New("Get token model error.")
	}

}